package net.citrite.android;

import com.android.annotations.Nullable;
import com.android.ide.common.rendering.api.ILayoutPullParser;
import com.android.ide.common.res2.ValueXmlHelper;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.*;
import java.util.Map;

import static com.android.SdkConstants.*;

@SuppressWarnings( "deprecation" )
public class XmlParser extends KXmlParser implements ILayoutPullParser {
    private String fragmentLayout;
    private ProjectCallback projectCallback;
    public XmlParser(ProjectCallback layoutlibCallback) {
        super();
        projectCallback = layoutlibCallback;
    }
    @SuppressWarnings( "deprecation" )
    public static XmlParser create(ProjectCallback layoutlibCallback,
                                              File xml) throws XmlPullParserException, IOException {
        XmlParser parser = new XmlParser(layoutlibCallback);
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        String xmlText = Files.toString(xml, Charsets.UTF_8);
        parser.setInput(new StringReader(xmlText));
        return parser;
    }
    @Override
    public Object getViewCookie() {
        String name = super.getName();
        if (name == null) {
            return null;
        }
//        System.out.println("name = " + name + ",line: " + getLineNumber() + ",column: "+ getColumnNumber());
        //projectCallback.updatePosition(getLineNumber(), name);
        if (LIST_VIEW.equals(name) || EXPANDABLE_LIST_VIEW.equals(name) || GRID_VIEW.equals(name) || SPINNER.equals(name)) {
            Map<String, String> map = null;
            int count = getAttributeCount();
            for (int i = 0; i < count; i++) {
                String namespace = getAttributeNamespace(i);
                if (namespace != null && namespace.equals(TOOLS_URI)) {
                    String attribute = getAttributeName(i);
                    if (attribute.equals(ATTR_IGNORE)) {
                        continue;
                    }
                    if (map == null) {
                        map = Maps.newHashMapWithExpectedSize(4);
                    }
                    map.put(attribute, getAttributeValue(i));
                }
            }
            return map;
        }
        return null;
    }

    @Override
    @Deprecated
    @SuppressWarnings("deprecation") // Required to support older layoutlib versions
    public ILayoutPullParser getParser(String layoutName) {
        String name = getName();
        System.out.println("name = " + name + ",line: " + getLineNumber() + ",column: "+ getColumnNumber());
        return projectCallback.getParser(layoutName);
    }

    @Override
    public String getName() {
        String name = super.getName();

        // At designtime, replace fragments with includes.
        if (name.equals(VIEW_FRAGMENT)) {
            fragmentLayout = super.getAttributeValue(TOOLS_URI, "layout");
            if (fragmentLayout != null) {
                return VIEW_INCLUDE;
            }
        }
        else {
            fragmentLayout = null;
        }
        return name;
    }

    @Nullable
    @Override
    public String getAttributeValue(String namespace, String localName) {
        if (ATTR_LAYOUT.equals(localName) && fragmentLayout != null) {
            return fragmentLayout;
        }

        String value = super.getAttributeValue(namespace, localName);

        // on the fly convert match_parent to fill_parent for compatibility with older
        // platforms.
        if (VALUE_MATCH_PARENT.equals(value) &&
                (ATTR_LAYOUT_WIDTH.equals(localName) || ATTR_LAYOUT_HEIGHT.equals(localName)) &&
                ANDROID_URI.equals(namespace)) {
            return VALUE_FILL_PARENT;
        }

        if (namespace != null) {
            if (namespace.equals(ANDROID_URI)) {
                // Allow the tools namespace to override the framework attributes at designtime
                String designValue = super.getAttributeValue(TOOLS_URI, localName);
                if (designValue != null) {
                    if (value != null && designValue.isEmpty()) {
                        // Empty when there is a runtime attribute set means unset the runtime attribute
                        value = null;
                    } else {
                        value = designValue;
                    }
                }
            } else if (value == null) {
                // Auto-convert http://schemas.android.com/apk/res-auto resources. The lookup
                // will be for the current application's resource package, e.g.
                // http://schemas.android.com/apk/res/foo.bar, but the XML document will
                // be using http://schemas.android.com/apk/res-auto in library projects:
                value = super.getAttributeValue(AUTO_URI, localName);
            }
        }

        if (value != null) {
            // Handle unicode and XML escapes
            for (int i = 0, n = value.length(); i < n; i++) {
                char c = value.charAt(i);
                if (c == '&' || c == '\\') {
                    value = ValueXmlHelper.unescapeResourceString(value, true, false);
                    break;
                }
            }
        }

        return value;
    }

//    @Override
//    public int next() throws XmlPullParserException, IOException {
//        int ret = super.next();
//        if (ret == XmlPullParser.START_TAG) {
//            String tagName = super.getName();
//            System.out.println("name = " + tagName + ",line: " + getLineNumber() + ",column: "+ getColumnNumber());
//        }
//        return ret;
//    }
}
